from rest_framework.views import exception_handler
from django.db import DatabaseError
from rest_framework.response import Response
from rest_framework import status
from redis import RedisError
import logging

logger = logging.getLogger('django')


def custom_exception_handler(exc, content):
    """
    :param exc:异常类
    :param content:抛出异常的上下文
    :return: Response响应对象
    """
    response = exception_handler(exc, content)

    if response is None:
        view = content['view']
        if isinstance(exc, DatabaseError):
            logger.error('[%s] %s' % (view, exc))
            response = Response({"message": "服务器内部错误"}, status=status.HTTP_507_INSUFFICIENT_STORAGE)

        elif isinstance(exc, RedisError):
            logger.error('redis数据库异常！[%s] %s' % (view, exc))
            response = Response({'message': '缓存服务器内部错误'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)
    return response
